package com.atguigu.gmall.user.controller;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author: 李旭
 * @create: 2021-09-06 14:15
 *
 *    登录判断校验
 *    http://api.gmall.com/api/user/passport/login
 **/
@RestController
@RequestMapping("/api/user/passport")
public class UserApiController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    //提交登录表单
    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo){
        //1:请输入账户名和密码
        if(null == userInfo || StringUtils.isEmpty(userInfo.getLoginName())
             || StringUtils.isEmpty(userInfo.getPasswd())){
            return Result.fail().message("请输入账户名和密码");
        }
        //2:校验用户名或密码是否正确
        userInfo = userInfoService.checkUserInfo(userInfo);
        //3:判断用户名密码是否正确
        if(null != userInfo){
            //4:保存用户信息到Redis缓存
            //4.1: Key就令牌    生成UUID   36位长度  四个小横线  去掉四个小横线 32位长度
            String token = UUID.randomUUID().toString().replaceAll("-", "");
            //4.2: Value 用户信息   用户ID
            //Map h = new HashMap   h.put(hk,hv) h.put(hk,hv) h.put(hk,hv) h.put(hk,hv)
            //redisTemplate.opsForHash().put("userInfo",token,userInfo.getId());
            redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX
                    + token,userInfo.getId().toString(),
                    RedisConst.USERKEY_TIMEOUT,TimeUnit.SECONDS);
            //JavaWeb Tomcat session 30分钟
            //5:   将token 带回浏览器  将昵称带回浏览器  回显
            Map result = new HashMap();
            result.put("token",token);
            result.put("nickName",userInfo.getNickName());
            return Result.ok(result);
        }else{
            //账户名或密码错误
            return Result.fail().message("账户名或密码错误");
        }
    }
    //查询当前用户的收货地址集合
    @GetMapping("/findUserAddressList")
    public List<UserAddress> findUserAddressList(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        return userInfoService.findUserAddressList(userId);

    }

}
